﻿
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using YDModel;
using YDServices.Comm;

namespace YDServices
{
    public class UserRoleService : BaseService
    {
        /// <summary>
        /// 获取角色绑定用户列表
        /// </summary>
        public List<T_Employee> getUserRole(long roleID)
        { 
             try
            {
                using (YDDataEntities db = new YDDataEntities())
                {
                    List<T_User_Role> list = db.T_User_Role.Where(o=>o.Role_ID==roleID).AsQueryable().ToList();

                    var lis = list.Join(db.T_Employee, o => o.User_ID, s => s.ID,
                        (o, s) => new T_Employee { EmployeeName= s.EmployeeName }
                    ).ToList(); 

                    return lis;
                }
            }
            catch (Exception ex)
            {
                Errors.Add(ex);
                WriteException(ex);
                return null;
            }
        }


        /// <summary>
        /// 获取用户权限
        /// </summary>
        public List<T_Permission> getUserPermission(long userID)
        {
            try
            {
                using (YDDataEntities db = new YDDataEntities())
                {
                    var userRole = db.T_User_Role.Where(o => o.User_ID == userID).AsQueryable().FirstOrDefault();
                    if(userRole!=null)
                    {
                        List<T_Permission> perlist = db.T_Permission.AsQueryable().ToList();
                        var roperlist = db.T_Role_Permission.Where(o => o.Role_ID == userRole.Role_ID).AsQueryable();
                        foreach (var roper in roperlist)
                        {
                            T_Permission per = perlist.Where(o => o.ID == roper.Permission_ID).FirstOrDefault();
                            if (per != null)
                            {
                                per.IsChecked = true;
                            }
                        }

                        return perlist;
                    }
                    else
                    {
                        throw new ApplicationException("该账号没有赋值权限,请联系管理员!");
                    }
 
                }
            }
            catch (Exception ex)
            {
                Errors.Add(ex);
                WriteException(ex);
                return null;
            }
        }


    }
}
